package cn.itcast.consumer.web;

import cn.itcast.consumer.config.RedisProperties;
import cn.itcast.provider.clients.UserClient;
import cn.itcast.provider.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 虎哥
 */
@RestController
@RequestMapping("consume")
public class ConsumerController {

    @Autowired
    private UserClient userClient;

    @Autowired
    private RedisProperties redisProperties;

    @GetMapping("hello")
    public RedisProperties redisProperties(){
        return redisProperties;
    }

    @GetMapping("{id}")
    public User queryById(@PathVariable("id") Long id) {
        // 其它业务
        User user = userClient.queryById(id);
        // 。。
        return user;
    }

//    @Autowired
//    private RestTemplate restTemplate;

    /*@HystrixCommand(fallbackMethod = "queryByIdFallback", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000")
    })
    @GetMapping("{id}")
    public Result queryById(@PathVariable("id") Long id){
        if(id == 1){
            throw new RuntimeException("我是故意的！");
        }
        // 请求路径：
        String url = "http://provider/user/" + id;
        // 发出一个get请求
        User user = restTemplate.getForObject(url, User.class);
        // 返回
        return Result.ok(user);
    }

    public Result queryByIdFallback(Long id){
        return Result.error("不好意思，服务器太拥挤了，稍后再试！");
    }*/



    /*@Autowired
    private DiscoveryClient discoveryClient;

    int index = 0;

    @GetMapping("{id}")
    public User queryById(@PathVariable("id") Long id) {
        // 拉取服务列表
        List<ServiceInstance> instances = discoveryClient.getInstances("provider");
        // 挑选一个，负载均衡
        int index = new Random().nextInt(instances.size());
        // index = (index+1) % instances.size();
        ServiceInstance instance = instances.get(index);
        // 获取ip和端口
        String host = instance.getHost();
        int port = instance.getPort();

        // 请求路径：
        String url = String.format("http://%s:%d/user/%d", host, port, id);
        // 发出一个get请求
        return restTemplate.getForObject(url, User.class);
    }*/

    /*@GetMapping("{id}")
    public User queryById(@PathVariable("id") Long id){
        // 请求路径：
        String url = "http://localhost:8081/user/" + id;
        // 发出一个get请求
        return restTemplate.getForObject(url, User.class);
    }*/
}
